package com.yy.wga.mp.module;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.yy.wga.mp.common.aop.NotLogin;
import com.yy.wga.mp.common.utils.common.StringUtils;
import com.yy.wga.mp.common.utils.mapping.BeansUtils;
import com.yy.wga.mp.module.income.dto.OrderCommissionDTO;
import com.yy.wga.mp.module.income.entity.pojo.IncomeOrderGoodsDO;
import com.yy.wga.mp.module.income.entity.pojo.IncomeUpGradeDO;
import com.yy.wga.mp.module.income.manager.OrderCommissionManager;
import com.yy.wga.mp.module.income.service.IncomeOrderGoodsService;
import com.yy.wga.mp.module.income.service.IncomeUpGradeService;
import com.yy.wga.mp.module.order.entity.pojo.OrderGoodsDO;
import com.yy.wga.mp.module.order.service.OrderGoodsService;
import com.yy.wga.mp.module.user.constant.RedisConstant;
import com.yy.wga.mp.module.user.entity.pojo.UserBaseDO;
import com.yy.wga.mp.module.user.entity.pojo.UserGradeRecordDO;
import com.yy.wga.mp.module.user.entity.pojo.UserRelationDO;
import com.yy.wga.mp.module.user.entity.pojo.UserSummaryDO;
import com.yy.wga.mp.module.user.enums.EUserGrade;
import com.yy.wga.mp.module.user.service.UserBaseService;
import com.yy.wga.mp.module.user.service.UserGradeRecordService;
import com.yy.wga.mp.module.user.service.UserRelationService;
import com.yy.wga.mp.module.user.service.UserSummaryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 测试接口
 *
 * @author guochao
 * @since 2022-11-01 19:08:37
 */
@Slf4j
@NotLogin
@RestController
@RequiredArgsConstructor
@RequestMapping("/test")
public class TestController {
    private final UserBaseService userBaseService;
    private final UserGradeRecordService userGradeRecordService;
    private final UserSummaryService userSummaryService;
    private final UserRelationService userRelationService;
    private final OrderGoodsService orderGoodsService;
    private final OrderCommissionManager orderCommissionManager;
    private final IncomeOrderGoodsService incomeOrderGoodsService;
    private final IncomeUpGradeService incomeUpGradeService;
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 生成用户关系链路
     *
     * @param userBaseList
     * @return
     */
    @PostMapping(value = "/generatorUserRelation")
    public Result<Boolean> generatorUserRelation(@RequestBody @Valid List<UserBaseDO> userBaseList) {
        Long parentUserId = null;
        Integer parentGrade = null;
        Integer parentLevel = null;
        for (int i = 0; i < userBaseList.size(); i++) {
            UserBaseDO userBase = userBaseList.get(i);
            Long userId = userBase.getId();
            userBaseService.realRemoveById(userId);
            userRelationService.removeByUserId(userId);
            userRelationService.removeByParentUserId(userId);

            Integer grade = userBase.getGrade();
            Integer level = userBase.getLevel();

            userBase.setAppKey("test");
            if (userBaseService.getById(userId) != null) {
                userBaseService.updateById(userBase);
            } else {
                userBaseService.save(userBase);
            }

            if (parentUserId != null) {
                UserRelationDO userRelationDO = new UserRelationDO();
                userRelationDO.setAppKey("test");
                userRelationDO.setParentUserId(parentUserId);
                userRelationDO.setParentGrade(parentGrade);
                userRelationDO.setParentLevel(parentLevel);
                userRelationDO.setUserId(userId);
                userRelationDO.setGrade(grade);
                userRelationDO.setLevel(level);
                userRelationService.save(userRelationDO);
            }
            parentUserId = userId;
            parentGrade = userBase.getGrade();
            parentLevel = userBase.getLevel();
        }
        return Result.success(Boolean.TRUE);
    }

    /**
     * 生成订单
     * @param orderCommissionDTO
     * @return
     */
    @PostMapping(value = "/generatorOrder")
    public Result<Boolean> generatorOrder(@RequestBody OrderCommissionDTO orderCommissionDTO) {
        // 保存订单
        OrderGoodsDO saveOrderGoods = BeansUtils.map(orderCommissionDTO, OrderGoodsDO.class);
        orderGoodsService.saveOrUpdate(saveOrderGoods);

        // 订单变更就需要重新分佣
        orderCommissionManager.commission(orderCommissionDTO);
        return Result.success(Boolean.TRUE);
    }

    /**
     * 查询订单分佣记录
     * @param orderNo 订单号
     * @return 订单分佣记录
     */
    @PostMapping(value = "/incomeList")
    public Result<List<IncomeOrderGoodsDO>> incomeList(@RequestParam("orderNo") String orderNo) {
        List<IncomeOrderGoodsDO> incomeOrderList = incomeOrderGoodsService.list(new LambdaQueryWrapper<IncomeOrderGoodsDO>()
                .eq(IncomeOrderGoodsDO::getOrderNo, orderNo));
        return Result.success(incomeOrderList);
    }

    /**
     * 查询用户最近下单的直通车订单分佣记录
     * @param userId 用户id
     * @return 订单分佣记录
     */
    @PostMapping(value = "/upgradeIncomeList")
    public Result<IncomeUpGradeDO> upgradeIncomeList(@RequestParam("userId") Long userId) {
        PageHelper.startPage(1, 1, false);
        IncomeUpGradeDO incomeUpGradeDO = incomeUpGradeService.getOne(new LambdaQueryWrapper<IncomeUpGradeDO>()
                .eq(IncomeUpGradeDO::getFromUserId, userId)
                .orderByDesc(IncomeUpGradeDO::getId));
        return Result.success(incomeUpGradeDO);
    }

    /**
     * 查询用户
     * @param userId 用户ID
     * @param phone 手机号
     * @return
     */
    @GetMapping(value = "/getUser")
    public Result<UserBaseDO> incomeList(@RequestParam(value = "userId", required = false) Long userId,
                                         @RequestParam(value = "phone", required = false) String phone) {
        if (userId == null && StringUtils.isBlank(phone)) {
            return Result.fail("两个你最少填一个行不");
        }
        UserBaseDO userBase = userBaseService.getOne(new LambdaQueryWrapper<UserBaseDO>()
                .eq(userId != null, UserBaseDO::getId, userId)
                .eq(StringUtils.isNotBlank(phone), UserBaseDO::getPhone, phone));
        return Result.success(userBase);
    }


    /**
     * 重置用户信息
     * @param userId 用户ID
     * @return
     */
    @GetMapping(value = "/resetUser")
    public Result<Boolean> resetUser(@RequestParam(value = "userId") Long userId) {
        UserBaseDO userBase = userBaseService.getOne(new LambdaQueryWrapper<UserBaseDO>()
                .eq(UserBaseDO::getId, userId));
        if (userBase == null) {
            return Result.fail("用户不存在");
        }
        userBase.setGrade(EUserGrade.SHARE_1.getType());
        userBase.setLevel(EUserGrade.SHARE_1.getType());
        userBaseService.updateById(userBase);

        userRelationService.removeByUserId(userId);
        userRelationService.removeByParentUserId(userId);
        userGradeRecordService.removeByUserId(userId);
        if (userSummaryService.getOne(new LambdaQueryWrapper<UserSummaryDO>()
                .eq(UserSummaryDO::getUserId, userId)) != null) {
            userSummaryService.update(new LambdaUpdateWrapper<UserSummaryDO>()
                    .eq(UserSummaryDO::getUserId, userId)
                    .set(UserSummaryDO::getSaleAmount, 0));
        }

        String userIdKey = RedisConstant.ACCOUNT_TOKEN + userId;
        String oldTokenKey = stringRedisTemplate.opsForValue().get(userIdKey);
        if (StringUtils.isNotBlank(oldTokenKey)) {
            stringRedisTemplate.delete(oldTokenKey);
        }
        stringRedisTemplate.delete(userIdKey);
        return Result.success(Boolean.TRUE);
    }

    /**
     * 新增下级用户
     * @return
     */
    @PostMapping(value = "/addChileUser")
    public Result<Boolean> addChileUser(@RequestBody JSONObject jsonObject) {
        Long userId = jsonObject.getLong("userId");
        Integer parentGrade = jsonObject.getInt("grade");
        Integer parentLevel = jsonObject.getInt("level");
        UserBaseDO user = new UserBaseDO();
        user.setId(userId);
        user.setAppKey("test");
        user.setGrade(parentGrade);
        user.setLevel(parentLevel);

        // 新增用户
        UserBaseDO userBaseDO = userBaseService.getOne(new LambdaQueryWrapper<UserBaseDO>()
                .eq(UserBaseDO::getId, userId));
        if (userBaseDO != null) {
            userBaseService.updateById(user);
        } else {
            userBaseService.save(user);
        }

        userRelationService.removeByParentUserId(userId);
        userRelationService.removeByUserId(userId);

        userGradeRecordService.removeByUserId(userId);
        UserGradeRecordDO userGradeRecord = new UserGradeRecordDO();
        userGradeRecord.setAppKey(user.getAppKey());
        userGradeRecord.setUserId(user.getId());
        userGradeRecord.setBeforeGrade(EUserGrade.COMMON.getType());
        userGradeRecord.setBeforeLevel(EUserGrade.COMMON.getLevel());
        userGradeRecord.setGrade(user.getGrade());
        userGradeRecord.setLevel(user.getLevel());
        userGradeRecordService.save(userGradeRecord);

        for (JSONObject child : jsonObject.getJSONArray("child").jsonIter()) {
            Long childUserId = child.getLong("userId");
            Integer grade = child.getInt("grade");
            Integer level = child.getInt("level");
            UserBaseDO childUser = new UserBaseDO();
            childUser.setId(childUserId);
            childUser.setAppKey("test");
            childUser.setGrade(parentGrade);
            childUser.setLevel(parentLevel);

            // 新增用户
            userBaseDO = userBaseService.getOne(new LambdaQueryWrapper<UserBaseDO>()
                    .eq(UserBaseDO::getId, childUserId));
            if (userBaseDO != null) {
                userBaseService.updateById(childUser);
            } else {
                userBaseService.save(childUser);
            }

            userRelationService.removeByParentUserId(childUserId);
            userRelationService.removeByUserId(childUserId);
            UserRelationDO userRelationDO = new UserRelationDO();
            userRelationDO.setAppKey("test");
            userRelationDO.setParentUserId(userId);
            userRelationDO.setParentGrade(grade);
            userRelationDO.setParentLevel(level);
            userRelationDO.setUserId(childUserId);
            userRelationDO.setGrade(grade);
            userRelationDO.setLevel(level);
            userRelationService.save(userRelationDO);

            userGradeRecordService.removeByUserId(childUserId);
            userGradeRecord = new UserGradeRecordDO();
            userGradeRecord.setAppKey(user.getAppKey());
            userGradeRecord.setUserId(childUserId);
            userGradeRecord.setBeforeGrade(EUserGrade.COMMON.getType());
            userGradeRecord.setBeforeLevel(EUserGrade.COMMON.getLevel());
            userGradeRecord.setGrade(grade);
            userGradeRecord.setLevel(level);
            userGradeRecordService.save(userGradeRecord);
        }
        return Result.success();
    }



//    @PostConstruct
//    public void a() {
////        List<String> phones = Arrays.asList("1395086888","13901201300","13600967828","17701686633","16621303058","18601692165","15711587433","13048052369","18817719131","13917101289","17274536143","18516761735","15800886840","19875778818","13906273898","13799288825","18685870318","19950627226","17365418786","19862381678","13559492831","17751723383");
//        List<String> phones = Arrays.asList("18221727029");
//        for (String phone : phones) {
//            UserBaseDO userBaseDO = userBaseService.getOne(new LambdaQueryWrapper<UserBaseDO>()
//                    .eq(UserBaseDO::getPhone, phone));
//            if (userBaseDO == null) {
//                log.info("用户不存在：{}", phone);
//                continue;
//            }
//            if (userBaseDO.getGrade() != 1) {
//                log.info("用户等级不正确：{}", phone);
//                continue;
//            }
//            UserBaseDO updateUser = new UserBaseDO();
//            updateUser.setId(userBaseDO.getId());
//            updateUser.setGrade(2);
//            updateUser.setLevel(2);
//            userBaseService.updateById(updateUser);
//
//            UserGradeRecordDO userGradeRecord = new UserGradeRecordDO();
//            userGradeRecord.setAppKey(userBaseDO.getAppKey());
//            userGradeRecord.setUserId(userBaseDO.getId());
//            userGradeRecord.setBeforeGrade(userBaseDO.getGrade());
//            userGradeRecord.setBeforeLevel(userBaseDO.getLevel());
//            userGradeRecord.setGrade(2);
//            userGradeRecord.setLevel(2);
//            userGradeRecordService.save(userGradeRecord);
//
//            userRelationService.update(new LambdaUpdateWrapper<UserRelationDO>()
//                    .eq(UserRelationDO::getUserId, userBaseDO.getId())
//                    .set(UserRelationDO::getGrade, 2)
//                    .set(UserRelationDO::getLevel, 2));
//            userRelationService.update(new LambdaUpdateWrapper<UserRelationDO>()
//                    .eq(UserRelationDO::getParentUserId, userBaseDO.getId())
//                    .set(UserRelationDO::getParentGrade, 2)
//                    .set(UserRelationDO::getParentLevel, 2));
//        }
//        log.info("success");
//    }
}
